import com.sun.source.tree.Tree;

public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;

    public void insert(int val){

        if(root == null){
            root = new TreeNode(val);
            return;
        }
        TreeNode node = new TreeNode(val);
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(node.val > cur.val){
                parent = cur;
                cur = cur.right;
            }else if(node.val < cur.val){
                parent = cur;
                cur = cur.right;
            }else{
                return;
            }

        }
        if(parent.val < node.val){
            parent.right = node;
        }else{
            parent.left = node;
        }
    }

    public TreeNode search(int val){
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < val){
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }

    public void remove(int key){
        TreeNode cur = root;
        TreeNode parent = root;
        while(cur.val != key){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else{
                parent = cur;
                cur = cur.left;
            }
        }
        if(cur.left == null){
            if(cur == root){
                root = root.right;
            }else if(cur.val < parent.val){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        } else if (cur.right == null) {
            if(cur == root){
                root = root.left;
            } else if (cur.val < parent.val) {
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            removeCur(cur,parent);
        }
    }

    private void removeCur(TreeNode target, TreeNode parent) {
        TreeNode tp = target;
        parent = target;
        target = target.right;

        while(target.left!= null){
            parent = target;
            target = target.left;
        }
        tp.val = target.val;
        if(parent.left == target){
            parent.left = target.right;
        }else{
            parent.right = target.right;
        }
    }

}
